package com.size.mall.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.size.mall.mallapi.entity.Member;
import com.size.mall.mallapi.entity.UmsMemberReceiveAddress;
import com.size.mall.mallapi.service.MemberService;
import com.size.mall.user.mapper.MemberMapper;
import com.size.mall.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2019-10-18
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public Member login(Member umsMember) {


        // 先从 redis 里面取
        Jedis jedis = null;
        try {
            //region 读缓存, 缓存击穿 或 缓存不存在查数据库
            jedis = redisUtil.getJedis();

            if (jedis != null) {
                String umsMemberStr = jedis.get("user:" + umsMember.getPassword()+umsMember.getUsername() + ":info");
                Member member = JSON.parseObject(umsMemberStr, Member.class);
                if (member != null) {

                    return member;
                }


            }
            //endregion

            QueryWrapper<Member> qw = new QueryWrapper<>();
            qw.ge("username", umsMember.getUsername());
            qw.ge("password", umsMember.getPassword());
            List<Member> members = baseMapper.selectList(qw);

            if (CollUtil.isNotEmpty(members)) {

                Member member = members.get(0);

                String jMember = JSON.toJSONString(member);

                if (jedis != null) {

                    jedis.set("user:" + member.getPassword() + ":info", jMember);
                }


                return member;

            } else {


            }


        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            jedis.close();
        }

        return null;
    }

    @Override
    public void addUserToken(String token, String memberId) {
        Jedis jedis = redisUtil.getJedis();

        if (jedis != null) {

            jedis.setex("user:" + memberId + ":token", 60 * 60 * 2, token);
            jedis.close();
        }
    }

    @Override
    public List<UmsMemberReceiveAddress> getMemberReceiveAddressByMemberId(String memberId) {
        return baseMapper.getMemberReceiveAddressByMemberId(memberId);
    }

    @Override
    public UmsMemberReceiveAddress getAddrByReciveAddressId(String receiveAddressId) {



        return baseMapper.getAddrByReciveAddressId(receiveAddressId);
    }
}
